﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Contract;
using System.Data.SqlClient;
using System.Data;
namespace Service
{
    class DataUploader : IDataUploader
    {

        SqlConnection con = new SqlConnection(service.Properties.Settings.Default.Database1ConnectionString1);

        public void Upload(MyFile Mf)
        {
            string ServerPath = Path.Combine("Storage", Mf.Name);
            using (FileStream fs = new FileStream(ServerPath, FileMode.Create))
        {
            int bufferSize = 1 * 1024 * 1024; // 1 MB buffer
            byte[] buffer = new byte[bufferSize];
            int bytes;

            while ((bytes = Mf.Value.Read(buffer, 0, bufferSize)) > 0)
            {
                fs.Write(buffer, 0, bytes);
                fs.Flush();
            }
            string query = "INSERT INTO Table1 (FILENAME) SELECT ('" + Mf.Name.ToString() + "') WHERE not exists(select * from Table1 where FILENAME =('" + Mf.Name.ToString() + "') )";
            SqlCommand insert = new SqlCommand(query, con);
            con.Open();
            insert.ExecuteNonQuery();
            con.Close();
        }
    }
     
        public Stream Download(string name)
        {
            string fPath = Path.Combine("Storage", name);

            if (!File.Exists(fPath))
                throw new FileNotFoundException("File was not found", Path.GetFileName(fPath));

            return new FileStream(fPath, FileMode.Open, FileAccess.Read);
           // return ReadFully(fs);
        }

        public void Delete(string name)
        {
            string serverPath = Path.Combine("Storage", name);

            if (File.Exists(serverPath))
            {
                File.Delete(serverPath);
            }
            string query = "DELETE FROM Table1 WHERE FILENAME='" +name + "'";
            SqlCommand delete = new SqlCommand(query, con);
            con.Open();
            delete.ExecuteNonQuery();
            con.Close();
        }

        public MyFile[] refreshList()
        {
            string query = "SELECT DISTINCT FILENAME FROM Table1";
            string checkCount = "SELECT COUNT(DISTINCT FILENAME) FROM Table1";
            SqlCommand getall = new SqlCommand(query, con);
            SqlCommand count = new SqlCommand(checkCount, con);
            
            
            con.Open();
            var num = count.ExecuteScalar();
            con.Close();
            
            
            con.Open();
            var read= getall.ExecuteReader();
        
            string names = "";

            int i = 0;
            MyFile[] mfs = new MyFile[Convert.ToInt32(num)];
            while (read.Read())
            {
                names = read["FILENAME"].ToString();
            
             
                MyFile mf = new MyFile() { Name = read["FILENAME"].ToString(), Size = 0, Value = null };//, mf.Size = 0, mf.Value = null };
                mfs[i] = mf;
                i++;
            }
         //   con.Close();

            string sb = "kuanbghao";
           
      
            con.Close();

            return mfs;

         //   return names;
        }

        public  MyFile[] Getfilesinfo(string filesPath)
        {
            string BasePath = "Storage";
            if (!string.IsNullOrEmpty(filesPath))
                BasePath  = Path.Combine("Storage", filesPath);
            DirectoryInfo dirInfo = new DirectoryInfo(BasePath);
            FileInfo[] files = dirInfo.GetFiles("*.*", SearchOption.AllDirectories);
            
            return (from f in files 
                    select new MyFile()
                    {  
                        Name = f.Name,
                        Size = f.Length,
                        Value = null
                    }).ToArray();
                   
        }

    }

    }

